package com.ciwong.mobilelib.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by res-mingyang on 2015/5/18.
 */
public abstract class FileUtil
{

    public static boolean isExistInSDCard(String url)
    {
        try
        {
            String changeUrl = subUrlEnd(url);
            File f = new File(BaseSystem.getImagePath() + changeUrl);
            return f.exists();
        }
        catch (Exception e)
        {
            return false;
        }
    }

    public static String subUrlEnd(String url)
    {

        try {
            int ll = url.lastIndexOf("/");
            return ll == -1 ? "" : url.substring(ll);
        } catch (NullPointerException e) {
            return null;
        }
    }

    /**
     * 合并Bitmap
     *
     * @param bitmap
     * @param bitmap1
     * @param path
     *            新Bitmap保存路径
     */
    public static void merger(Bitmap bitmap, Bitmap bitmap1, String path)
    {
        if (bitmap != null)
        {
            Bitmap bitmap2 = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), bitmap.getConfig());
            Canvas canvas = new Canvas(bitmap2);
            Paint paint = new Paint();
            paint.setAlpha(150);
            canvas.drawBitmap(bitmap, new Matrix(), null);
            if (bitmap1 != null)
            {
                canvas.drawBitmap(bitmap1, 0, 0, null);
            }
            FileUtil.saveBitmapToSDCard(bitmap2, path);
        }
    }

    public static void saveBitmapToSDCard(Bitmap mBitmap, String url)
    {
        if (mBitmap == null || mBitmap.isRecycled())
        {
            return;
        }
        File f = new File(BaseSystem.getImagePath() + subUrlEnd(url));
        FileOutputStream fOut = null;
        try
        {
            fOut = new FileOutputStream(f);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            fOut.flush();
            fOut.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static Bitmap getBitmapFromSDCard(String url)
    {
        String lastUrl = BaseSystem.getImagePath() + subUrlEnd(url);
        return getLocalOrNetBitmap(lastUrl);
    }

    /**
     * 得到本地或者网络上的bitmap url - 网络或者本地图片的绝对路径,比如:
     *
     * A.网络路径: url="http://blog.foreverlove.us/girl2.png" ;
     *
     * B.本地路径:url="file://mnt/sdcard/photo/image.png";
     *
     * C.支持的图片格式 ,png, jpg,bmp,gif等等
     *
     * @param url
     * @return
     */
    public static Bitmap getLocalOrNetBitmap(String url)
    {
        if (!url.startsWith("http://"))
        {
            url = "file:///" + url;
        }
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try
        {
            in = new BufferedInputStream(new URL(url).openStream(),
                    IO_BUFFER_SIZE);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;
            return bitmap;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    private static void copy(InputStream in, OutputStream out)
            throws IOException
    {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1)
        {
            out.write(b, 0, read);
        }
    }

    static final int IO_BUFFER_SIZE = 1024;

    /**
     * 通过反射调用某个类某个方法并获取返回值
     * 
     * @param className
     * @param methodName
     * @return
     */
    public static Object reflectInvoke(String className, String methodName,
            Class[] classes, Object... objects)
    {
        Object value = "";
        try
        {
            Class<?> clazz = Class.forName(className);
            Method method = clazz.getDeclaredMethod(methodName, classes);
            method.setAccessible(true);
            value = method.invoke(clazz.newInstance(), objects);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 递归获取文件夹大小
     *
     * @param file
     *            File实例
     * @return long
     */
    public static long getFolderSize(java.io.File file)
    {
        long size = 0;
        try
        {
            java.io.File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++)
            {
                if (fileList[i].isDirectory())
                {
                    size = size + getFolderSize(fileList[i]);
                }
                else
                {
                    size = size + fileList[i].length();
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return size;
    }
    public static Uri uri;
    public static File createImageFile(Context context, boolean isCrop) {
        try {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String fileName = "";
            if (isCrop) {
                fileName = "IMG_"+timeStamp+"_CROP.jpg";
            } else {
                fileName = "IMG_"+timeStamp+".jpg";
            }
            File rootFile = new File(context.getExternalFilesDir(null).getAbsoluteFile() + File.separator + "capture");
            if (!rootFile.exists()) {
                rootFile.mkdirs();
            }
            File imgFile;
            if (Build.VERSION.SDK_INT >= 30) {
                imgFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + fileName);
                // 通过 MediaStore API 插入file 为了拿到系统裁剪要保存到的uri（因为App没有权限不能访问公共存储空间，需要通过 MediaStore API来操作）
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, imgFile.getAbsolutePath());
                values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            }else {
                imgFile = new File(rootFile.getAbsolutePath() + File.separator + fileName);
            }
            return imgFile;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static File getCropFile(Context context, Uri uri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);

        if (cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            String path = cursor.getString(columnIndex);
            cursor.close();
            return new File(path);
        }
        return null;
    }
}
